<?php

namespace App\Models\ChatGroup;

use App\Library\Rms\RmsUserApi;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class ChatGroupHistoryModel extends BaseModel
{
    protected $fillable = [
        'clientMsgId',
        'shopId',
        'groupId',
        'sessionId',
        'senderUid',
        'content',
        'type',
        'recall',
        'recallUid',
        'sensitive',
        'isAnswer',
        'isSendAi',
        'isRecordStatistics'
    ];

    protected $table = 'chat_group_history';

    // text/images/lists/tips
    const TYPE_TEXT     = 'text';
    const TYPE_IMAGES   = 'images';
    const TYPE_VIDEOS   = 'videos';
    const TYPE_FAQ      = 'faq'; // 已废弃
    const TYPE_FAQ_V2   = 'faqV2';
    const TYPE_FILES    = 'files';
    const TYPE_DIALOG   = 'dialog';
    const TYPE_TIPS     = 'tips';
    const TYPE_APPRAISE = 'appraise';

    const TYPES = [
        self::TYPE_TEXT     => '文本',
        self::TYPE_IMAGES   => '图片',
        self::TYPE_VIDEOS   => '视频',
        self::TYPE_FAQ      => '常见问题', // 已废弃
        self::TYPE_TIPS     => '提示',
        self::TYPE_APPRAISE => '好评卡',
        self::TYPE_FAQ_V2   => '常见问题',
        self::TYPE_FILES    => '文件',
        self::TYPE_DIALOG   => '对话框',
    ];

    // 已撤回
    const RECALL_NO  = 0;
    const RECALL_YES = 1;

    // 是否发送 AI
    const IS_SEND_AI_YES = 1;
    const IS_SEND_AI_NO  = 0;

    // 是否记录统计数
    const IS_RECORD_COUNT_YES = 1;
    const IS_RECORD_COUNT_NO  = 0;


    // 敏感词
    const SENSITIVE_YES = 1;

    const NOT_ANSWER = 0;
    const GET_ANSWER = 1;

    const ANSWER_TEXT_MAPPING = [
        self::NOT_ANSWER => '无答案',
        self::GET_ANSWER => '存在答案',
    ];

    /**
     * 创建消息
     * @param string $clientMsgId
     * @param int $groupId
     * @param int $shopId
     * @param int $sessionId
     * @param int $senderUid
     * @param string $content
     * @param string $type
     * @param int $sensitive
     * @param int $isSendAi
     * @return Builder|Model
     */
    public function add(
        string $clientMsgId,
        int $groupId,
        int $shopId,
        int $sessionId,
        int $senderUid,
        string $content,
        string $type,
        int $sensitive,
        int $isSendAi,
        int $isRecordStatistics
    ) {
        // 判断 content 中是否有答案
        $isAnswer = BaseModel::DEFAULT_NO;
        if (isJson($content)) {
            $contentData = json_decode($content, 1);

            // 判断 content 中是否有答案
            if (!empty($contentData['btn'][0]['params']['indexNumber'])) {
                $isAnswer = BaseModel::DEFAULT_YES;

                ChatGroupSessionModel::updateColumn(['id' => $sessionId], ['isAnswer' => BaseModel::DEFAULT_YES]);
            }
        }


        return ChatGroupHistoryModel::query()->create([
            'clientMsgId'        => $clientMsgId,
            'groupId'            => $groupId,
            'shopId'             => $shopId,
            'sessionId'          => $sessionId,
            'senderUid'          => $senderUid,
            'content'            => $content,
            'type'               => $type,
            'recall'             => 0,
            'recallUid'          => 0,
            'sensitive'          => $sensitive,
            'isSendAi'           => $isSendAi,
            'isAnswer'           => $isAnswer,
            'isRecordStatistics' => $isRecordStatistics
        ]);
    }

    public function getContentFormatAttribute()
    {
        // 字符串
        if (!isJson($this->content)) {
            return (string)$this->content;
        }

        // json
        $arr = json_decode($this->content, true);

        // 评价卡要填充最新的评价
        if ($this->type == self::TYPE_APPRAISE) {
            $appraises = ChatGroupSessionAppraiseModel::query()
                                                      ->where('sessionId', $this->sessionId)
                                                      ->get()
                                                      ->keyBy('uid')->toArray();

            foreach ($arr as &$val) {
                $val = [
                    'user_id' => $val['user_id'],
                    'score'   => $appraises[$val['user_id']]['score'] ?? 0,
                    'solve'   => $appraises[$val['user_id']]['solve'] ?? 0,
                ];
            }
        }

        return $arr;
    }

    /**
     * 列表中的senderUid数组
     * @var array
     */
    public array $listSenderUid = [];

    /**
     * 生成消息结构体
     * 有发送人，使用前需要设置$listSenderUid !!!
     * @return array
     */
    public function getChatStruct(): array
    {
        $arr = [
            'msgId'              => $this->id,
            "groupId"            => $this->groupId,
            'clientMsgId'        => $this->clientMsgId,
            'type'               => $this->type,
            'content'            => [$this->type => $this->contentFormat],
            'recall'             => $this->recall,
            'sensitive'          => $this->sensitive,
            'time'               => $this->createdAt->timestamp,
            'isRecordStatistics' => $this->isRecordStatistics
        ];

        if (!$this->senderUid) {
            return $arr;
        }

        // 有发送人的消息
        if ($this->listSenderUid) {
            $userIds = $this->listSenderUid;
        } else {
            $userIds = [$this->senderUid];
        }

        $name = $avatar = '';

        // 查询总部人员alias、avatar
        $groupUsers = ChatGroupUserModel::getGroupUsers($this->groupId, ChatGroupUserModel::ROLE_KF)
                                        ->keyBy('userId');

        $groupUser = $groupUsers[$this->senderUid] ?? null;
        if ($groupUser) {
            $name    = $groupUser->alias;
            $avatar  = $groupUser->avatar;
            $tagText = $groupUser->tagText;
        }

        // api获取用户信息
        if (!$name || !$avatar) {

            $users = $this->getUserApi($userIds);

            if (!$name) {
                $name = $users[$this->senderUid]['username'] ?? '';
            }

            if (!$avatar) {
                $avatar = $users[$this->senderUid]['avatar'] ?? '';
            }
        }

        $arr['user'] = [
            'id'      => $this->senderUid,
            'name'    => $name,
            'avatar'  => $avatar,
            'tagText' => $tagText ?? '',
        ];

        return $arr;
    }

    public function getText(): string
    {
        switch ($this->type) {
            case self::TYPE_TEXT:
            case self::TYPE_TIPS:
                return $this->content;
            case self::TYPE_IMAGES:
                return '[图片]';
            case self::TYPE_VIDEOS:
                return '[视频]';
            case self::TYPE_FAQ:
            case self::TYPE_FAQ_V2:
                return '[常见问题]';
            case self::TYPE_APPRAISE:
                return '[评价]';
            case self::TYPE_FILES:
                return '[文件]';
            case self::TYPE_DIALOG:
                $data = json_decode($this->content, true);
                return "[" . ($data['title'] ?? '') . "]";
            default:
                return '';
        }
    }

    private function getUserApi(array $userIds): array
    {
        // 加缓存
        if (count($userIds) == 1) {
            return Cache::remember("getUserApi:" . $userIds[0], 600, function () use ($userIds) {
                return array_column((new RmsUserApi())->getUserInfoByIds($userIds,
                    ['id', 'username', 'avatar'])['data'] ?? [], null, 'id');
            });
        }

        return array_column((new RmsUserApi())->getUserInfoByIds($userIds,
            ['id', 'username', 'avatar'])['data'] ?? [], null, 'id');
    }
}
